package com.yuesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuesystem.common.BaseContext;
import com.yuesystem.common.R;
import com.yuesystem.dto.requestbody.GradeRequestBody;
import com.yuesystem.dto.responsebody.OfficeNumberResponseBody;
import com.yuesystem.dto.responsebody.OfficeSearchResponseBody;
import com.yuesystem.entity.ChangeItem1;
import com.yuesystem.entity.Office;
import com.yuesystem.entity.OfficeItem;
import com.yuesystem.service.ChangeItem1Service;
import com.yuesystem.service.OfficeItemService;
import com.yuesystem.service.OfficeService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import com.yuesystem.service.impl.FeedbackServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 官职控制类.
 */
@RestController
@RequestMapping("/offices")
@CrossOrigin
@Slf4j
public class OfficeController {
  @Autowired
  private OfficeService officeService;
  
  @Autowired
  private OfficeItemService officeItemService;
  
  @Autowired
  private ChangeItem1Service changeItem1Service;
  
  /**
   * 增加官职.
   */
  @RequestMapping("/add")
  public R<String> addOffice(@RequestBody Office office) {
    if (office.getOfficeName() == null) {
      return R.error("官职名不为空");
    }
    if (office.getCorpus() == null) {
      return R.error("官职介绍不为空");
    }
    if (officeService.add(office)) {
      ChangeItem1 changeItem1 = new ChangeItem1();
      changeItem1.setUserId(FeedbackServiceImpl.userId);
      changeItem1.setOperate("增加");
      changeItem1.setSubjectNew(office.getOfficeName());
      changeItem1.setRelationNew("介绍");
      changeItem1.setObjectNew(office.getCorpus());
      changeItem1Service.save(changeItem1);
      return R.success("添加成功");
    }
    return R.error("官职已存在，添加失败");
  }
  
  /**
   * 删除官职.
   */
  @RequestMapping("/delete")
  public R<String> deleteOffice(@RequestParam Long id) {
    Office office = officeService.getById(id);
    if (office == null) {
      return R.error("删除失败");
    }
    List<OfficeItem> list = officeItemService.getItems(id);
    for (OfficeItem officeItem : list) {
      officeItem.setIsDeleted(1);
      officeItemService.updateById(officeItem);
    }
    ChangeItem1 changeItem1=new ChangeItem1();
    changeItem1.setUserId(FeedbackServiceImpl.userId);
    changeItem1.setOperate("删除");
    changeItem1.setSubjectOld(office.getOfficeName());
    changeItem1.setRelationOld("介绍");
    changeItem1.setObjectOld(office.getCorpus());
    changeItem1Service.save(changeItem1);
    officeService.removeById(office);
    return R.success("删除成功");
  }
  
  /**
   * 更改corpus内容
   */
  @PostMapping("/update")
  public R<String> update(@RequestBody Office office1) {
    Long id = office1.getId();
    String corpus = office1.getCorpus();
    Office office = officeService.getById(id);
    if (office == null) {
      return R.error("更改失败");
    }
    if (corpus == null) {
      return R.error("介绍不为空");
    }
    String oldCorpus=office.getCorpus();
    office.setCorpus(corpus);
    officeService.updateById(office);
    ChangeItem1 changeItem1=new ChangeItem1();
    changeItem1.setUserId(FeedbackServiceImpl.userId);
    changeItem1.setOperate("修改");
    changeItem1.setSubjectOld(office.getOfficeName());
    changeItem1.setRelationOld("介绍");
    changeItem1.setObjectOld(oldCorpus);
    changeItem1.setSubjectNew(office.getOfficeName());
    changeItem1.setRelationNew("介绍");
    changeItem1.setObjectNew(office.getCorpus());
    changeItem1Service.save(changeItem1);
    return R.success("编辑成功");
  }
  
  /**
   * 根据官职名称来搜索对应的官职，返回一个官职类集合.
   *
   * @param name     官职名称
   * @param page     页面个数
   * @param pageSize 页面大小
   * @return 官职类集合
   */
  @GetMapping("/search")
  public R<Page<OfficeSearchResponseBody>> search(@RequestParam String name, @RequestParam int page,
                                                  @RequestParam int pageSize) {
    Page<Office> pageInfo = new Page<>(page, pageSize);
    Page<OfficeSearchResponseBody> page1 = new Page<>(page, pageSize);
    LambdaQueryWrapper<Office> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.like(name != null || !name.isEmpty(), Office::getOfficeName, name);
    officeService.page(pageInfo, queryWrapper);
    
    // 对象拷贝，把pageInfo的内容拷贝进dtoPage，忽略records，就是第三个参数中写的那样
    BeanUtils.copyProperties(pageInfo, page1, "records");
    List<Office> records = pageInfo.getRecords();
    
    List<OfficeSearchResponseBody> list = records.stream().map((item) -> {
      OfficeSearchResponseBody body = new OfficeSearchResponseBody();
      body.setId(item.getId());
      body.setOfficeName(item.getOfficeName());
      if (item.getCorpus().length() > 60) {
        body.setSimpleCorpus(item.getCorpus().substring(0, 60) + "......");
      } else {
        body.setSimpleCorpus(item.getCorpus());
      }
      return body;
    }).collect(Collectors.toList());
    
    page1.setRecords(list);
    
    return R.success(page1);
  }
  
  
  /**
   * 获得某个年代、品阶的官职分布情况.
   *
   * @param dynastyGrade 朝代品阶
   * @param page         页面个数
   * @param pageSize     页面大小
   * @return 该朝代品阶的所有官职
   */
  @GetMapping("/distribute/{dynasty_grade}/{page}/{pageSize}")
  public R<Page<OfficeSearchResponseBody>> getDistribute(
      @PathVariable(name = "dynasty_grade") String dynastyGrade,
      @PathVariable int page, @PathVariable int pageSize) {
    Page<Office> pageInfo = officeService.getPage(page, pageSize, dynastyGrade);
    Page<OfficeSearchResponseBody> page1 = new Page<>(page, pageSize);
    
    BeanUtils.copyProperties(pageInfo, page1, "records");
    List<Office> records = pageInfo.getRecords();
    
    List<OfficeSearchResponseBody> list = records.stream().map((item) -> {
      OfficeSearchResponseBody body = new OfficeSearchResponseBody();
      body.setId(item.getId());
      body.setOfficeName(item.getOfficeName());
      if (item.getCorpus().length() > 60) {
        body.setSimpleCorpus(item.getCorpus().substring(0, 60) + "......");
      } else {
        body.setSimpleCorpus(item.getCorpus());
      }
      return body;
    }).collect(Collectors.toList());
    
    page1.setRecords(list);
    
    return R.success(page1);
  }
  
  /**
   * 获得某个年代、品阶的官职分布情况.
   *
   * @param dynasty  朝代
   * @param grade    品阶
   * @param page     页面个数
   * @param pageSize 页面大小
   * @return 该朝代品阶的所有官职
   */
  @GetMapping("/distribute1/{dynasty}/{grade}/{page}/{pageSize}")
  public R<Page<OfficeSearchResponseBody>> getDistribute1(
      @PathVariable(name = "dynasty") String dynasty, @PathVariable(name = "grade") String grade,
      @PathVariable int page, @PathVariable int pageSize) {
    Page<Office> pageInfo = officeService.getPage1(page, pageSize, dynasty, grade);
    Page<OfficeSearchResponseBody> page1 = new Page<>(page, pageSize);
    
    BeanUtils.copyProperties(pageInfo, page1, "records");
    List<Office> records = pageInfo.getRecords();
    
    List<OfficeSearchResponseBody> list = records.stream().map((item) -> {
      OfficeSearchResponseBody body = new OfficeSearchResponseBody();
      body.setId(item.getId());
      body.setOfficeName(item.getOfficeName());
      if (item.getCorpus().length() > 60) {
        body.setSimpleCorpus(item.getCorpus().substring(0, 60) + "......");
      } else {
        body.setSimpleCorpus(item.getCorpus());
      }
      return body;
    }).collect(Collectors.toList());
    
    page1.setRecords(list);
    
    return R.success(page1);
  }
  
  /**
   * 根据官职id获得官职信息.
   *
   * @param id 官职id
   * @return 官职主体
   */
  @GetMapping("/{id}")
  public R<Office> getById(@PathVariable Long id) {
    Office office = officeService.getById(id);
    return R.success(office);
  }
  
  /**
   * 获得朝代+品阶分布.
   *
   * @return 所有的朝代品阶分布
   */
  @GetMapping("/grades")
  public R<List<GradeRequestBody>> getByGrade() {
    List<GradeRequestBody> list = officeService.getByGrade();
    return R.success(list);
  }
  
  /**
   * 获得各朝代书院数目.
   */
  @GetMapping("/number")
  public R<List<OfficeNumberResponseBody>> getNumber() {
    List<OfficeNumberResponseBody> list = officeService.getNumber();
    return R.success(list);
  }
  
  /**
   * 随机获得八个官职推荐.
   *
   * @return 八个官职列表
   */
  @GetMapping("/introduce")
  public R<List<Office>> introduce() {
    Random random = new Random();
    List<Integer> numberList = new ArrayList<>();
    
    while (numberList.size() < 8) {
      Integer number = random.nextInt(500);
      if (!numberList.contains(number)) {
        numberList.add(number);
      }
    }
    List<Office> officeList = new ArrayList<>();
    for (Integer i : numberList) {
      Office office = officeService.getById(i);
      officeList.add(office);
    }
    
    return R.success(officeList);
  }
  
  /**
   * 返回所有朝代对应的各个品阶数目.
   */
  @GetMapping("/allGradesNumber")
  public R<Map<String, List<OfficeNumberResponseBody>>> getAllGradesNumber() {
    List<String> dynastyList = Arrays.asList("汉代", "三国魏", "晋代", "南朝宋", "南朝梁",
        "南朝陈", "北魏", "北齐", "北周", "隋朝", "唐朝", "宋代", "金朝", "元代", "明代", "清代");
    Map<String, List<OfficeNumberResponseBody>> map = new HashMap<>();
    for (int i = 0; i < dynastyList.toArray().length; i++) {
      List<OfficeNumberResponseBody> list = new ArrayList<>();
      list = officeService.getGradeNumber(i);
      map.put(dynastyList.get(i), list);
    }
    return R.success(map);
  }
  
  /**
   * 返回某个朝代对应的各个品阶数目.
   */
  @GetMapping("/gradeNumber")
  public R<Map<String, List<OfficeNumberResponseBody>>> getGradeNumber(@RequestParam int index) {
    List<String> dynastyList = Arrays.asList("汉代", "三国魏", "晋代", "南朝宋", "南朝梁",
        "南朝陈", "北魏", "北齐", "北周", "隋朝", "唐朝", "宋代", "金朝", "元代", "明代", "清代");
    String dynasty = dynastyList.get(index);
    Map<String, List<OfficeNumberResponseBody>> map = new HashMap<>();
    List<OfficeNumberResponseBody> list = new ArrayList<>();
    list = officeService.getGradeNumber(index);
    map.put(dynasty, list);
    return R.success(map);
  }
  
}
